package com.tuocent.dagv2.common.utils;


import com.tuocent.dagv2.entity.ArchivesClass;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@UtilityClass
public class ArchivesClassTreeUtil {
    public <T extends ArchivesClass> List<T> build(List<T> treeNodes, String root) {
        List<T> trees = new ArrayList<>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(treeNode);
            }
            for (T node : treeNodes) {
                if (node.getParentId().equals(treeNode.getId())) {
                    List<ArchivesClass> childrens = treeNode.getChildren();
                    if (childrens == null) {
                        childrens = new ArrayList<>();
                    }
                    childrens.add(node);
                    treeNode.setChildren(childrens);
                }
            }
        }
        return trees;
    }

    public <T extends ArchivesClass> List<T> modifyClassCode(List<T> treeNodes, String root) {
        List<T> trees = build(treeNodes, root);
        List<T> classData = new ArrayList<>();
        for (T node : trees) {
            if (node.getChildren() == null) {
                classData.add(node);
            } else {
                classData.addAll((Collection<? extends T>) buildCode(node.getChildren(), node.getFullCode()));
            }
        }
        return classData;
    }

    public List<ArchivesClass> buildCode(List<ArchivesClass> treeNodes, String pCode) {
        List<ArchivesClass> classData = new ArrayList<>();
        for (ArchivesClass node : treeNodes) {
            node.setPcode(pCode);
            node.setFullCode(pCode + node.getDoc() + node.getCode());
            classData.add(node);
            if (node.getChildren() != null) {
                classData.addAll(buildCode(node.getChildren(), node.getFullCode()));
            }
        }
        return classData;
    }
}
